package com.admin.web;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.admin.service.AdminProfileService;
import com.common.model.AdminUser;
import com.common.model.BaseUser;
import com.common.util.Md5Encrypt;


/**
 * 管理员个人主页,包括个人密码修改,个人信息维护.
 * @author yww
 *
 */
@Controller
@RequestMapping("/admin/profile")
public class AdminProfileWeb {
	@Autowired
	AdminProfileService service;
	private static final Logger logger = LoggerFactory.getLogger(AdminProfileWeb.class);
	/**
	 * 显示管理员个人主页
	 * @return
	 */
	@RequestMapping("")
	public ModelAndView showIndex(HttpSession session){
		ModelAndView mav=new ModelAndView();
		mav.setViewName("admin/profile/index");
		mav.addObject("currentMenu", "home");
		return mav;
	}
	/**
	 *更改用户信息
	 * @param admin  新的信息（原用户id，电话，性别，姓名）
	 * @param session
	 * @return 成功返回0
	 */
	@ResponseBody
	@RequestMapping("/updateInfo")
	public int updateInfo(AdminUser admin,HttpSession session ){
		logger.info("admin "+admin.getId()+" is updating info");
		BaseUser user=(BaseUser)session.getAttribute("user");
		if(user.getId()!=admin.getId()){//防止某一个管理员利用这个功能更改其他用户的信息
			logger.warn("user is not correct,id in session is "+user.getId()+" ,but input id is "+admin.getId());
			return -1;
		}
		if(admin.getName().trim().isEmpty()){
			logger.warn("user's name is empty which is not allowed");
			return -2;
		}
		logger.info("udate info success,id: "+admin.getId()+" new gender: "+admin.getGender()+" new tel: "+admin.getTelephone()+"new name: "+admin.getName());
		service.updateInfo(admin, session);
		return 0;
	}
	/**
	 *更改密码
	 * @param admin  新的信息（原用户id，电话，性别，姓名）
	 * @param session
	 * @return 成功返回0
	 */
	@ResponseBody
	@RequestMapping("/updatePass")
	public int updatePass(int id,String oldPass,String newPass,HttpSession session ){
		logger.info("admin "+id+" is updating password");
		BaseUser user=(BaseUser)session.getAttribute("user");
		if(user.getId()!=id){//防止某一个管理员利用这个功能更改其他用户的信息
			logger.warn("user is not correct,id in session is "+user.getId()+" ,but input id is "+id);
			return -1;
		}
		if(oldPass.trim().isEmpty()||newPass.trim().isEmpty()){
			logger.warn("oldPass or newPass is empty");
			return -2;
		}
		if(!Md5Encrypt.check(user.getPassword(), oldPass)){
			logger.warn("oldPass is not correct");
			return -3;
		}
		logger.info("udate pass success,id: "+id);
		service.updatePass(id, Md5Encrypt.encrypt(newPass), session);
		return 0;
	}
}
